/**
* Name: Ex L8f - schelling
* Author: Gudrun Wallentin
* Description: CA Building block model to model dynamic environments
* Tags: schelling, segregation
*/
model ExL8fschelling

global torus: true{
	
	//Percentage of similar wanted for segregation
	float percent_similar_wanted <- 0.5 ;
	//number of people: counted from the grid, which is created before the global init
	int number_of_people;
	//reporter variable
	float percent_unhappy;

	init {
		//count the actual population
		number_of_people <- length(homes where (each.color != #black));
		ask homes where (each.color != #black){
			do update ;
		}
		percent_unhappy <- 100 * length(homes where (each.is_unhappy = true)) / number_of_people;		
	}
	
	reflex migrate {
		ask homes where (each.color != #black){
			do update ;
		}
		percent_unhappy <- 100 * length(homes where (each.is_unhappy = true)) / number_of_people;

		ask shuffle(homes where (each.is_unhappy = true)) {
			//migrate to an empty black spot
			ask one_of (shuffle(homes where (each.color = #black))){
				color <- myself.color;	
				myself.color <- #black;
				myself.is_unhappy <- false;							
			}
		}
	}
}

//Grid species representing the places and the people in each cell
grid homes width: 40 height: 40 neighbors: 8  {
	rgb color <- #black;
	int similar_nearby;
	int total_nearby;
	bool is_unhappy <- false;
	list<homes> my_neighbours;
	
	init {
		if flip (0.7){
			color <- one_of ([#red, #green]);
		}
	}
	
	action update {
		//List of the neighbouring homes
		my_neighbours <- self.neighbors;
		similar_nearby <- (my_neighbours count (each.color = color));
		//number of total neighbours nearby
		total_nearby <- length (my_neighbours);
		is_unhappy <- similar_nearby < (percent_similar_wanted * total_nearby ) ;	
	}
}

experiment schelling type: gui {
	parameter "Desired percentage of similarity:" var: percent_similar_wanted min: float (0) max: float (1) ;
	output {
		display Segregation type:2d antialias:false{
			grid homes;
		}

		display Charts  type: 2d {
			chart "Share of unhappy settlers" type: series background: #lightgray axes: #white {
				data "unhappy" color: #blue value: percent_unhappy style: spline;
			}
		}
	}
}
